/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.motion
{
	import com.qb9.flashlib.geom.Vector2D;
	import com.qb9.flashlib.interfaces.IUpdateable;
	
	/**
	 * This class includes properties to store velocity,
	 * acceleration and angular velocity. The update() method updates
	 * all properties.
	 *
	 * @see examples/motion/MotionExample.as.
	 */
	public class Motion implements IUpdateable
	{
		/**
		 * Position
		 */
		public var position:Vector2D;
		public function get x():Number {return position.x};
		public function get y():Number {return position.y};
		public function set x(v:Number):void {position = new Vector2D(v, y)};
		public function set y(v:Number):void {position = new Vector2D(x, v)};
		
		/**
		 * Velocity (units / second).
		 */
		public var velocity:Vector2D;
		
		/**
		 * Acceleration (units / second²).
		 */
		public var acceleration:Vector2D;

		/**
		 * Angular velocity (units / second).
		 */
		public var angularVelocity:Number;
		
		/**
		 * Maximum velocity
		 */
		public var maxVelocity:Number;
		
		/**
		 * rotation (degrees or radians, you choose).
		 */
		public var rotation:Number;

		public function Motion()
		{
			position = new Vector2D();
			velocity = new Vector2D();
			acceleration = new Vector2D();
			rotation = 0;
		}

		/**
		 * Update the position, velocity and rotation.
		 *
		 * @param milliseconds Amount of milliseconds that passed since the last call.
		 *             Use (1000.0 / stage.frameRate) if calling once per frame.
		 */
		public function update(milliseconds:uint):void
		{
			var secs:Number = milliseconds / 1000.0;
			velocity = velocity.add(acceleration.scaled(secs));
			
			if (maxVelocity && velocity.norm2 > maxVelocity * maxVelocity)
				velocity = velocity.normalized(maxVelocity);
			
			position = position.add(velocity.scaled(secs));
			if (angularVelocity)
				rotation += angularVelocity * secs;
		}
	}
}
